﻿using System;
using System.Windows;
using WiMo.Games.Audio;

namespace WiMo.Games.StandardAudio
{
    public class AudioManager : IAudioManager
    {
        public AudioManager(IGameEngine engine)
        {
            Engine = engine;
        }

        private AudioManager() { }

        private IGameAudio GetGameAudio(string name)
        {
            var assembly = Engine.Game.GetType().Assembly;

            var assemblyName = assembly.FullName.Substring(0, assembly.FullName.IndexOf(','));

            var contentPath = string.Format(@"{0};component/{1}/{2}", assemblyName, Engine.ContentManager.ContentLocation, name);
            var contentUri = new Uri(contentPath, UriKind.Relative);

            var sr = Application.GetResourceStream(contentUri);
            if (sr == null)
                return null;

            return new GameAudio(sr.Stream, Engine); ;
        }

        public IGameAudio LoadSong(string name)
        {
            var audio = GetGameAudio(String.Format("{0}.mp3", name));
            if (audio != null)
                return audio;

            audio = GetGameAudio(String.Format("{0}.wma", name));
            if (audio != null)
                return audio;

            throw new NullReferenceException(string.Format("Could not find content: {0}.mp3 or {0}.wma, note: Since we are loading from a resource, the extension must be lowercase and the name must match the case of the file.", name));
            
        }

        public IGameAudio LoadSound(string name)
        {
            return LoadSong(name);
        }

        public IGameEngine Engine { get; private set; }
    }
}
